package com.dingpeikeji.quickdeer.modules.base.web;

import java.io.IOException;
import java.net.URLEncoder;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.druid.support.json.JSONUtils;
import com.dingpeikeji.quickdeer.core.common.config.Global;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Office;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Role;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.core.modules.sys.service.SystemService;
import com.dingpeikeji.quickdeer.modules.base.entity.WxParam;
import com.dingpeikeji.quickdeer.modules.base.entity.QqParam;
import com.dingpeikeji.quickdeer.modules.base.service.FrontUserService;
import com.dingpeikeji.quickdeer.modules.utils.ValidateCodeTool;
import com.dingpeikeji.quickdeer.modules.utils.ValidateTool;
import com.dingpeikeji.quickdeer.utils.JedisClient;
import com.dingpeikeji.quickdeer.utils.StringUtil;
import com.google.common.collect.Lists;

import net.sf.json.JSONObject;
/**
 * 一些信息
 *
 */
@Controller
@RequestMapping("/f/info")
public class FInfoController {
	public static final String FRONT_USER_IN_WX = "wx";
	public static final String FRONT_USER_IN_SESSION = "front_user";
	@Autowired
	private FrontUserService userService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private JedisClient jedisClient;
	/**
	 * 加入我们
	 * @return
	 */
	@RequestMapping("joinUs")
	public String joinUs() {
		return "modules/base/joinUsInfo";
	}
	@RequestMapping("wxlogin")
	public void wxLogin(HttpServletResponse response) throws IOException {
		String backUrl = "https://www.xiakeyueche.com/f/info/callBack";
        String url = "https://open.weixin.qq.com/connect/qrconnect?"
                + "appid=" + AuthUtil.APPID
                + "&redirect_uri=" + URLEncoder.encode(backUrl)
                + "&response_type=code"
                + "&scope=snsapi_login"
                + "&state=STATE"
                + "#wechat_redirect";
        response.sendRedirect(url);
	}
	@RequestMapping("qqlogin")
	public void qqLogin(HttpServletResponse response) throws IOException {
		String backUrl = "https://www.xiakeyueche.com/f/info/qqcallBack";
		String url = "https://graph.qq.com/oauth2.0/authorize?"
				+ "client_id=" + AuthUtil.QQAPPID
				+ "&redirect_uri=" + URLEncoder.encode(backUrl)
				+ "&response_type=code"
				+ "&scope=get_user_info"
				+ "&state=STATE";
		response.sendRedirect(url);
	}
	
	@RequestMapping("/qqcallBack")
	public String qqcallBack(HttpServletRequest request,Model model,
			RedirectAttributes redirectAttributes,HttpServletResponse response) throws IOException, ServletException {
		String backUrl = "https://www.xiakeyueche.com/f/info/qqcallBack";
		String code = request.getParameter("code");
		String url = "https://graph.qq.com/oauth2.0/token?"
				+ "client_id=" + AuthUtil.QQAPPID
				+ "&client_secret=" + AuthUtil.QQAPPKEY
				+ "&code=" + code
				+ "&grant_type=authorization_code&redirect_uri="+backUrl;
		String result = AuthUtil.doGetString(url);
		String[] arr = result.split("&");
		String accesstoken = arr[0].substring("access_token=".length());
		//2. 向微信发出请求，带上APPSCECRET和code，获取openid和access_toekn
		String infoUrl = "https://graph.qq.com/oauth2.0/me?"
        		+ "access_token=" + accesstoken;
		result = AuthUtil.doGetString(infoUrl);
		String json = result.substring(result.indexOf("{"), result.lastIndexOf("}")+1);
		JSONObject jsStr = JSONObject.fromObject(json);
		String openid = jsStr.getString("openid");
		String userInfoUrl = "https://graph.qq.com/user/get_user_info?"
        		+ "access_token=" + accesstoken+"&oauth_consumer_key="+AuthUtil.QQAPPID+"&openid="+openid;
		result = AuthUtil.doGetString(userInfoUrl);
		JSONObject userInfo = JSONObject.fromObject(result);
		String loginName = userService.getLoginNameByQqOpenid(openid);
		QqParam qqParam = new QqParam(openid, userInfo);
		if ("".equals(loginName) || loginName == null) {
			// 未绑定。 跳转到绑定页面，要求用户输入账户密码
			request.setAttribute("user", qqParam);
			request.getRequestDispatcher("/bindqq.jsp").forward(request, response);
			return null;
		} else {
			// 已绑定。直接跳转登录成功页面
			User user = userService.getUserByLoginName(loginName);
			HttpSession session = request.getSession();
			session.setAttribute(FRONT_USER_IN_SESSION, user);
			return "redirect:/f/index";
		}
	}
	
	@RequestMapping("/callBack")
	public String callBack(HttpServletResponse response,HttpServletRequest request,Model model,
			RedirectAttributes redirectAttributes) throws IOException, ServletException {
		 	String code = request.getParameter("code");
	        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
	                    + "appid=" + AuthUtil.APPID
	                    + "&secret=" + AuthUtil.APPSECRET
	                    + "&code=" + code
	                    + "&grant_type=authorization_code";
	        //2. 向微信发出请求，带上APPSCECRET和code，获取openid和access_toekn
	        JSONObject jsonObject = AuthUtil.doGetJson(url);
	        String openid = jsonObject.getString("openid");
	        String token = jsonObject.getString("access_token");
	        //4. 获取用户信息
	        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?"
	        		+ "access_token=" + token
	        		+ "&openid=" + openid
	        		+ "&lang=zh_CN";
	        JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
	        System.out.println(userInfo);
	        String unionid = userInfo.getString("unionid");
	        String loginName = userService.getLoginName(unionid);
	        WxParam wxParam = new WxParam(unionid, userInfo);
			if ("".equals(loginName)||loginName==null){
				//未绑定。 跳转到绑定页面，要求用户输入账户密码
				//更新数据库openid
				request.setAttribute("user", wxParam);
				request.getRequestDispatcher("/bindWx.jsp").forward(request, response);
				return null;
			} else {
				//已绑定。直接跳转登录成功页面
				User user = userService.getUserByLoginName(loginName);
				HttpSession session = request.getSession();
				session.setAttribute(FRONT_USER_IN_SESSION, user);
				return "redirect:/f/index";
			}
	}
	
	@RequestMapping(value="bindqq",method=RequestMethod.POST)
	public String bindQq(HttpServletRequest request, HttpServletResponse response,Model model,String validateCode) throws IOException, ServletException {
		String loginName =request.getParameter("loginName");
		String openid =request.getParameter("openid");
		String password =request.getParameter("confirmNewPassword");
		List<String> messages = Lists.newArrayList(); // 消息
        String mobileFromRedisCode = jedisClient.get("registercode: "+loginName);
		if (StringUtil.isEmpty(mobileFromRedisCode)) {
			messages.add("短信验证码超时");
		}
		if (!mobileFromRedisCode.equals(validateCode)) {
			messages.add("短信验证码错误");
		}
		if(!messages.isEmpty()||StringUtils.isEmpty(loginName)||StringUtils.isEmpty(openid)) { // 验证码校验不通过
			request.getSession().setAttribute("mes", "验证码不正确,请重新登录");
			return "redirect:/bindqq.jsp";
		}
		//数据库中已经有loginname
		User user = userService.getUserByLoginName(loginName);
		if (user!=null) {
			userService.updateUserByOPenID(openid,loginName);
			System.out.println("账号绑定成功");
			HttpSession session = request.getSession();
			session.setAttribute(FRONT_USER_IN_SESSION, user);
			return "redirect:/f/index";
		}else{
			//没有loginname,需要注册
			User qqUser = new User();
			Office company = new Office();
			company.setId(Global.getConfig("front.companyid"));//0
			Office office = new Office();
			office.setId(Global.getConfig("front.officeid"));// "-"
			qqUser.setCompany(company);
			qqUser.setOffice(office);
			qqUser.setLoginName(loginName);
			qqUser.setName(loginName);
			qqUser.setPassword(SystemService.entryptPassword(password));
			List<Role> roleList = Lists.newArrayList();
			Role r = new Role();
			r.setId(Global.getConfig("front.roleid"));//2
			roleList.add(r);
			qqUser.setRoleList(roleList);
			systemService.savePubUser(qqUser);
			userService.updateUserByOPenID(openid,loginName);
			System.out.println("账号绑定成功");
			HttpSession session = request.getSession();
			session.setAttribute(FRONT_USER_IN_SESSION, qqUser);
			return "redirect:/f/index";
		}
	}
	@RequestMapping(value="bindWx",method=RequestMethod.POST)
	public String bindWx(HttpServletRequest request, HttpServletResponse response,Model model,String validateCode) throws IOException, ServletException {
		String loginName =request.getParameter("loginName");
        String unionid =request.getParameter("unionid");
        String password =request.getParameter("confirmNewPassword");
        List<String> messages = Lists.newArrayList(); // 消息
        String mobileFromRedisCode = jedisClient.get("registercode: "+loginName);
		if (StringUtil.isEmpty(mobileFromRedisCode)) {
			messages.add("短信验证码超时");
		}
		if (!mobileFromRedisCode.equals(validateCode)) {
			messages.add("短信验证码错误");
		}
		//List<String> validateCodeMsg = ValidateCodeTool.validateFromPhone(request, validateCode, FSmsController.validateCodeTypes[0]);
		if(!messages.isEmpty()||StringUtils.isEmpty(loginName)||StringUtils.isEmpty(unionid)) { // 验证码校验不通过
			request.getSession().setAttribute("mes", "验证码不正确,请重新登录");
			return "redirect:/bindWx.jsp";
		}
      	//数据库中已经有loginname
        User user = userService.getUserByLoginName(loginName);
        if (user!=null) {
        	userService.updateUserByUnionID(unionid,loginName);
        	System.out.println("账号绑定成功");
        	HttpSession session = request.getSession();
        	session.setAttribute(FRONT_USER_IN_SESSION, user);
			return "redirect:/f/index";
		}else{
			//没有loginname,需要注册
			User wxUser = new User();
			Office company = new Office();
			company.setId(Global.getConfig("front.companyid"));//0
			Office office = new Office();
			office.setId(Global.getConfig("front.officeid"));// "-"
			wxUser.setCompany(company);
			wxUser.setOffice(office);
			wxUser.setLoginName(loginName);
			wxUser.setName(loginName);
			wxUser.setPassword(SystemService.entryptPassword(password));
			List<Role> roleList = Lists.newArrayList();
			Role r = new Role();
			r.setId(Global.getConfig("front.roleid"));//2
			roleList.add(r);
			wxUser.setRoleList(roleList);
			systemService.savePubUser(wxUser);
			userService.updateUserByUnionID(unionid,loginName);
			System.out.println("账号绑定成功");
			HttpSession session = request.getSession();
        	session.setAttribute(FRONT_USER_IN_SESSION, wxUser);
			return "redirect:/f/index";
		}
	}
	
	public void checkTel(HttpServletRequest req, HttpServletResponse resp,Model model) throws IOException {
		String tel =req.getParameter("tel");
		//数据库中已经有loginname
		User user = userService.getUserByLoginName(tel);
		if (user!=null) {
			resp.getWriter().print(1);
		}else{
			resp.getWriter().print(0);
		}
	}
	/**
	 * 免责说明
	 * @return
	 */
	@RequestMapping("disclaimer")
	public String disclaimer() {
		return "modules/base/disclaimerInfo";
	}
	
	/**
	 * 用户须知
	 * @return
	 */
	@RequestMapping("understand")
	public String understand() {
		return "modules/base/understandInfo";
	}
	
	/**
	 * 用户注册
	 * @return
	 */
	@RequestMapping("register")
	public String register() {
		return "modules/base/registerInfo";
	}
	
	/**
	 * 约车流程
	 * @return
	 */
	@RequestMapping("flow")
	public String flow() {
		return "modules/base/flowInfo";
	}
	
	/**
	 * 关于我们
	 * @return
	 */
	@RequestMapping("aboutUs")
	public String aboutUs() {
		return "modules/base/aboutUsInfo";
	}
	
	/**
	 * 关于我们
	 * @return
	 */
	@RequestMapping("applycargo")
	public String applycargo() {
		return "modules/base/applycargo";
	}
	
}
